library(tidyverse)
library(purrr)
library(sf)
doit <- function(model = "reward", subset = TRUE,
                 match = "primary", covars = 1,
                 family = "gaussian") {

    if (subset) {
        dat <- subset(dat, PriorityGrouping != "High")
    }
    dat$Funded <- as.numeric(dat$Funded == "Yes")

    f <- Funded ~ Rank + Region
    if (model == "reward") {
        if (match == "primary") {
            f <- update(f, . ~ . + ConWinner1.primary)
        } else if (match == "weighted") {
            f <- update(f, . ~ . + ConWinner.weighted)
        } else {
            f <- update(f, . ~ . + ConWinner1.allm)
        }
    } else {
        if (match == "primary") {
            f <- update(f, . ~ . + abs(ConMaj.primary))
        } else if (match == "weighted") {
            f <- update(f, . ~ . + abs(ConMaj.weighted))
        } else {
            f <- update(f, . ~ . + abs(ConMaj.allm))
        }
    }
    if (covars == 1) {
        f <- f
    } else {
        f <- update(f, . ~ . + log(Pop) +
                           Quals + IncomeDep + Brexit + Productivity + Shocks +
                           Investment + Alignment)
    }

    glm(f, data = dat, family = family)
            
}

testrig <- expand.grid(model = c("reward", "swing"),
            subset = c(FALSE, TRUE),
            family = c("gaussian", "binomial"),
            covars = c(1, 2),
            match = c("primary", "weighted", "all"))

dat <- readRDS("../working/selection_data.rds") %>%
    st_drop_geometry()

res <- apply(testrig, 1,
      function(x)doit(model = x["model"],
                      subset = x["subset"],
                      family = x["family"],
                      covars = x["covars"],
                      match  = x["match"]))

testrig$AIC <- unlist(lapply(res, AIC))

plot.df <- testrig %>%
    group_by(subset, family, covars,match) %>%
    summarize(delta = AIC[model == "swing"] - AIC[model == "reward"])

ggplot(plot.df, aes(x = match, y = delta,
                    fill = family)) +
    geom_col(position = position_dodge()) +
    facet_grid(subset ~ covars)
